package puc.redes.examples.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPThreadClient {
	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	TCPThreadClient() {
	}

	void run() {
		try {
			// 1. Creamos un socker de conexion con el servidor
			requestSocket = new Socket("localhost", 2512);
			System.out.println("Conectados a localhost, puerto 2512");
			
			// o lo hacemos mediante DNS lookup
//			InetAddress ipaddress = InetAddress.getByName("www.google.cl");
//			requestSocket = new Socket(ipaddress.getHostAddress(), 2512);

			// 2. obtenermos los stream de entrada y salida del socker
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());

			// 3: Nos comunicamos con el servidor
			do {
				try {
					message = (String) in.readObject();
					System.out.println("servidor: " + message);
					if (message.equals("Conexion exitosa")) {
						// enviamos mensajes
						sendMessage("hola servidor");
					} else if (message.equals("chau")) {
						message = "chau";
						sendMessage(message);
					} else if (message.equals("envio de datos")){
						message = "fin recepcion datos";
						sendMessage(message);
					} 
					else if (message.equals("ok")){
						message = "chau";
						sendMessage(message);
					} else {
						System.out.println("mensaje erroneo: " + message);
					}
				} catch (ClassNotFoundException classNot) {
					System.err
							.println("Datos recibidos en formato desconocido");
				}
			} while (!message.equals("chau"));
		} catch (UnknownHostException unknownHost) {
			System.err.println("desconozco el host!");
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			// 4: Cerramos la conexion
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("cliente: " + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void main(String args[]) {
		TCPThreadClient client = new TCPThreadClient();
		client.run();
	}

}
